package com.tang.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.Date;

@Slf4j
public class MyServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 连接
     * 
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel socketChannel = (SocketChannel) ctx.channel();
        log.info("链接报告开始");
        log.info("链接报告信息：有一个客户端链接到本服务端");
        log.info("链接报告IP：{}", socketChannel.localAddress().getHostString());
        log.info("链接报告Port：{}", socketChannel.localAddress().getPort());
        log.info("链接报告完毕！");
        // 通知客户端链接建立成功
        String str = "通知客户端链接建立成功！" + " " + new Date() + " " 
                + socketChannel.localAddress().getHostString() + "\r\n";
        ctx.writeAndFlush(str);
    }

    /**
     * 断开连接
     * 
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端断开链接, {}", ctx.channel().localAddress().toString());
    }

    /**
     * 获取客户端发送的信息
     * 
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("{} 接收到消息 {}", LocalDateTime.now(), msg);
        String str = "服务端收到消息：" + LocalDateTime.now() + " " + msg + "\r\n";
        ctx.writeAndFlush(str);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        log.info("异常信息：\r\n{}", cause.getMessage());
    }
}
